require 'yaml'
require 'rdiscount'

class Document

  class << self
    def load(dir, ext="md")
      @documents ||= {}
      @dirname=dir
      Dir.glob("#{dir}/**/*.#{ext}").each do |file|
        document = Document.new(file)
        document.set_path()
        @documents[document.slug] = document
      end
    end

    def [](slug)
      @documents[slug]
    end

    def documents
      @documents #.values.sort.reverse
    end

    def get(path)
      document=@documents.select { |k,v| k.end_with?("#{path}.md") }
      if document.nil? || document.size>1
         #nil
         document.first
      end
    end
  end

  def initialize(file_path)
    @file_path = file_path

    yaml = File.new(file_path).lines.take_while{ |line| !line.strip.empty? }
    @offset = yaml.length

    @options = YAML.load(yaml.join)
  end

  %w(title description rel_path).each do |m|
    class_eval "def #{m};@options['#{m}'];end"
  end

  def [](key)
    @options[key.to_s]
  end

  def slug
    File.basename(@file_path, ".*")
  end

  def body
    RDiscount.new(content).to_html
  end

  def summary
    RDiscount.new(content[0..100]).to_html
  end

  #relative_path
  def set_path
    tmp=@file_path.gsub(/.(\w+)$/,'')
    doc_path="documents"
    if !tmp.nil? && tmp.length>0
      @options["rel_path"]=tmp.slice(tmp.index(doc_path)+(doc_path.length),tmp.length)
    end
  end

  def set_baseurl(relative_path='/',with_slug=false)
    if with_slug && !relative_path.end_with?('/','\\')
      relative_path="#{relative_path}/#{slug}"
    end
    @url=relative_path
  end

  def path
    @options["rel_path"]
  end

  def to_hash
    Hash[%w(title description rel_path body summary).map{ |key| [key.intern, self.send(key)] }]
  end

  private
  def content
    return @content if instance_variable_defined?("@content")
    File.new(@file_path).lines.drop(@offset).join
  end

end